<template>
    <div class="main-content">
        <echartsLayout :formState='formState' :dataListState='dataListState' :eCharts1State='eCharts1State' :eCharts2State='eCharts2State' 
        :eCharts3State='eCharts3State' :chartsListState='chartsListState' :tableState='tableState'>
            <div slot="form">
                <el-form :model="query" ref="query" label-width="40px" label-position="right">
                    <el-row :gutter="41">
                        <el-col :span="7">
                            <el-form-item label="日期">
                                <el-row>
                                    <el-col :span="11">
                                        <el-date-picker v-model="query.startDate" :clearable="false" :editable="false" type="date" placeholder="选择开始日期" :picker-options="pickerOptions1" @change="startDateChange" style="width:100%"></el-date-picker>
                                    </el-col>
                                    <el-col :span="2" align="center">-</el-col>
                                    <el-col :span="11">
                                        <el-date-picker v-model="query.endDate" :clearable="false" :editable="false" type="date" placeholder="选择结束日期" :picker-options="pickerOptions2" @change="endDateChange" style="width:100%"></el-date-picker>
                                    </el-col>
                                </el-row>  
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <div class="top-line">
                                <el-button type="primary" class="btn-common" @click="onSubmit">查询</el-button>
                            </div>
                        </el-col>
                    </el-row> 
                </el-form>
            </div> 
            <div slot="eCharts1" >
                <div class="charts-title">用户手机分辨率分布</div>
                <div class="charts-display">
                    <trendChart width='100%' height='100%' id="barChart1" :option='barChart1Option'></trendChart>
                </div>
            </div>
            <div slot="table" >
                <div class="table-title">
                    <!-- <el-button @click="exportExcel" class="btn-common">导出</el-button> -->
                    <export-excel :jsonStr="jsonStr"></export-excel>
                </div> 
                <el-table :data="tableData" border v-loading="loading" style="width: 100%" @sort-change="sortTable">
                    <el-table-column label="分辨率" align="center">
                        <template scope="scope">
                            <span>{{scope.row.screen | isNull}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="用户总数" align="center" sortable="custom" prop="user_total">
                        <template scope="scope">
                            <span>{{ scope.row['user_total'] | isNull }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="教学app用户数" align="center" sortable="custom" prop="teacher">
                        <template scope="scope">
                            <span>{{scope.row.teacher | isNull}}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="家庭app用户数" align="center" sortable="custom" prop="parent">
                        <template scope="scope">
                            <span>{{scope.row.parent| isNull}}</span>
                        </template>
                    </el-table-column>

                    <!-- <el-table-column label="报表日期" align="center">
                        <template scope="scope">
                            <span>{{scope.row.className | isNull}}</span>
                        </template>
                    </el-table-column> -->
                </el-table>
                <div class="pagination-container">
                    <el-pagination
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageQuery.total"
                        :current-page.sync="pageQuery.currentpage"
                        :page-sizes="config.pageSizes"
                        :page-size="config.pageSize"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </div>
        </echartsLayout>
    </div>
</template>

<script>
    import moment from 'moment';
    import exportExcel from 'components/ExportExcel/index';
    import trendChart from 'components/Charts/trendChart';
    import echartsLayout from 'components/TableLayout/echartsLayout'; 
    import { mapState, mapActions } from 'vuex';
    export default{
        components: {echartsLayout, trendChart, exportExcel },
        data() {
            return {
                loading: false,
                formState: false,
                dataListState: true,
                eCharts1State: false,
                eCharts2State: true,
                eCharts3State: true,
                chartsListState: true,
                tableState: false,
                query: {
                    startDate: moment().subtract(30, 'days').format('YYYY-MM-DD'),
                    endDate: moment().subtract(1, 'days').format('YYYY-MM-DD')
                },
                tableData: [],
                pageQuery: {
                    currentpage: 1,
                    total: 0
                },
                pickerOptions1: null,
                pickerOptions2: null,
                barChart1Option: null,
                sortType: '',
                isDesc: true,
                jsonStr: null,
                queryId: 48,
                realTime: false,
                showList: true
            }
        },
        computed: {
            ...mapState({
                config: state => state.config.table
            })
        },
        created() {
            this.queryData();

        },
        methods: {
            ...mapActions(['ChangePageSize']),
            handleSizeChange(val) {
                this.pageQuery.currentpage = 1;
                this.ChangePageSize(val);
                // this.queryData();
                this.setTable();
            },
            handleCurrentChange(val) {
                this.pageQuery.currentpage = val;
                // this.queryData();
                this.setTable();
            },
            queryData() {
                this.setMap();
                this.setTable();
               
            },


            setMap() {
                let startDate = this.query.startDate==''?moment().subtract(30, 'days').format('YYYY-MM-DD'):moment(this.query.startDate).format('YYYY-MM-DD'); 
                let endDate = this.query.endDate==''?moment().subtract(1, 'days').format('YYYY-MM-DD'):moment(this.query.endDate).format('YYYY-MM-DD'); 
                let query = {'measures': [{'event_name': '$AppEnd', 'aggregator': 'unique'}], 'unit': 'day', 'by_fields': ['event.$AppEnd.$screen_height', 'event.$AppEnd.$screen_width'], 'sampling_factor': 64, 'from_date': startDate, 'to_date': endDate, 'tType': 'n', 'ratio': 'n', 'approx': false, 'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'filter': {}, 'detail_and_rollup': true, 'use_cache': true, 'request_id': 1515660136649};
                let inforSent = {
                    query_id: this.queryId,
                    real_time: this.realTime,
                    type: 'bar',
                    formInline: 'day',
                    query,
                    barBorderRadius: 6
                };

                this.getList(inforSent);
            },

            setTable() {
                let startDate = this.query.startDate==''?moment().subtract(30, 'days').format('YYYY-MM-DD'):moment(this.query.startDate).format('YYYY-MM-DD'); 
                let endDate = this.query.endDate==''?moment().format('YYYY-MM-DD'):moment(this.query.endDate).format('YYYY-MM-DD'); 
                this.sortType = this.sortType=== ''?'user_total':this.sortType;
                let query = {
                    'order_field': this.sortType,
                    'order_desc': this.isDesc,
                    'from_date': startDate,
                    'to_date': endDate, 
                    'tType': 'n',
                    'use_cache': true, 
                    'detail_and_rollup': true, 
                    'filter': {},
                    'measures': [{'aggregator': 'unique', 'event_name': '$AppEnd'}],
                    'unit': 'day', 
                    'by_fields': ['event.$AppEnd.$screen_height', 'event.$AppEnd.$screen_width', 'event.$AppEnd.loginEnd'], 
                    'sampling_factor': 64, 
                    'axis_config': {'isNormalize': false, 'left': [], 'right': []}, 'request_id': 1516343465849, 'ratio': 'n', 'approx': false, 'group': {'group_fields': ['event.$AppEnd.$screen_width', 'event.$AppEnd.$screen_height'], 'key_field': 'event.$AppEnd.loginEnd', 'value_field': '$AppEnd.unique'}
                }
                let inforSent = {
                    query_id: this.queryId,
                    real_time: this.realTime,
                    type: 'bar',
                    formInline: 'day',
                    query,
                    barBorderRadius: 6,
                    showList: this.showList,
                    page_index: this.pageQuery.currentpage,
                    page_size: this.config.pageSize
                };
                
                // 导出
                let file_name ='用户手机分辨率分布';
                let field_names = [['分辨率', 'screen'], ['用户总数', 'user_total'], ['教学app用户数', 'teacher'], ['家庭app用户数', 'parent']];
                this.jsonStr = {
                    query_id: this.queryId,
                    real_time: this.realTime,
                    query,
                    show_list: this.showList,
                    file_name,
                    field_names

                }

                this.getList(inforSent);
            },


            getList(inforSent) {
                this.loading = true;
                this.$store.dispatch('getQuery', inforSent).then((data) => {
                    this.loading = false;
                    if (data.data.rollup_result) {
                        let dataTemp = data.data.rollup_result.rows.slice(0, 10);
                        let xAxisData = [];
                        let barList =[];
                        dataTemp.forEach(item => {
                            xAxisData.push(item.by_values[0]+'*'+item.by_values[1]);
                            barList.push(item.values[0][0]);
                        })
                        this.barChart1Option = {
                            color: ['#2EC7C9'],
                            tooltip: {
                                trigger: 'axis'
                            },
                            legend: {
                                data: ['用户数']
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                            },
                            xAxis: [
                                {
                                    type: 'category',
                                    data: xAxisData,
                                    axisLabel: {
                                        interval: 0
                                    }
                                }
                            ],
                            yAxis: [
                                {
                                    type: 'value'
                                }
                            ],
                            series: [
                                {
                                    name: '用户数',
                                    type: 'bar',
                                    data: barList,
                                    itemStyle: {
                                        normal: {
                                            barBorderRadius: 6
                                        } 
                                    }
                                }
                            ]
                        };
                    } else {
                        this.tableData = data.data.rows;
                        this.pageQuery.total = data.data.total || data.data.total_rows;

                    }
                });
            },


            onSubmit() {
                this.pageQuery.currentpage = 1;
                this.queryData();
            },
            exportExcel() {
                console.log('导出');
            },
            startDateChange(date) {
                this.pickerOptions2 = {
                    disabledDate(time) {
                        return (time.getTime() < new Date(date).getTime() - 864e5);
                    }
                }
            },
            endDateChange(date) {
                this.pickerOptions1 = {
                    disabledDate(time) {
                        return (time.getTime() > new Date(date).getTime());
                    }
                } 
            },

            sortTable(params) {
                this.sortType = params.prop;
                params.order === 'ascending'?this.isDesc = false:this.isDesc = true;
                this.setTable();
            }
        }
    }
</script>
<style lang="scss" scoped>
    .main-content {
        position: relative;
        $bgcolor: #fff;
    }
</style>                     